<template>
    <div class="course-table-container">
        <div class="date-header">
            <div class="current-date">{{ currentDate }}
                <span v-if="isCurrentWeek" style="color: red;">本周</span>
            </div>
            <div class="week-navigation">
                <button @click="prevWeek">上一周</button>
                <button @click="nextWeek">下一周</button>
            </div>
        </div>

        <table>
            <thead>
                <tr>
                    <th>时间/星期</th>
                    <th v-for="day in days" :key="day">
                        {{ getZH(day) }}<br>{{ getDayDate(day) }}
                    </th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(time, index) in times" :key="index">
                    <td>{{ time }}</td>
                    <td class="select_btn" v-for="day in days" :key="day">
                        <!-- 选择框 -->
                        <el-select 
                            v-model="courseData[day][index]" 
                            :style="courseData[day][index] ? {
                                '--el-text-color-regular': '#ff0000',
                                '--el-disabled-text-color': '#ff0000'
                            } : {}"
                            placeholder="选择课程" 
                            clearable
                            :disabled="isDateBeforeToday(getDayDate(day))">
                            <el-option v-for="item in courseList" :key="item.courseId"
                                :label="`${item.courseName}_${item.teacherName}`" :value="JSON.stringify({
                                    courseId: item.courseId,
                                    courseName: item.courseName,
                                    teacherId: item.teacherId,
                                    teacherName: item.teacherName
                                })" />
                        </el-select>
                    </td>
                </tr>
            </tbody>
        </table>
        <div class="buttons">
            <button v-if="old" @click="submitCourseTable">提交</button>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue';
import { updateCurriculumScheduleService, getCurriculumScheduleService } from '@/apis/curriculumSchedule';
import { getCourseListService } from '@/apis/course'
import { ElMessage } from 'element-plus';
import { initChatWebSocket, disconnectChatWebSocket } from '@/apis/chat';

const currentWeekStart = ref(new Date());
// WebSocket 连接状态
const wsConnected = ref(false);

// 初始化 WebSocket 连接，接收实时课程表更新
const initWebSocket = () => {
    // 初始化 WebSocket 连接
    const result = initChatWebSocket();
    
    if (result) {
        wsConnected.value = true;
        console.log('课程表 WebSocket 连接成功');
        
        // 订阅课程表更新事件
        window.addEventListener('curriculum_update', handleCurriculumUpdate);
    } else {
        console.error('无法建立课程表 WebSocket 连接');
    }
};

// 处理课程表更新事件
const handleCurriculumUpdate = (event) => {
    // 检查更新的课程表是否与当前显示的班级和周次匹配
    const updateData = event.detail;
    if (updateData && updateData.classroomId === classroomId.value) {
        // 如果是当前正在查看的班级的更新，则刷新课程表
        ElMessage.info('课程表已更新，正在刷新...');
        getCurriculumSchedule();
    }
};

// 在组件卸载时清理 WebSocket 连接
onUnmounted(() => {
    // 移除事件监听器
    window.removeEventListener('curriculum_update', handleCurriculumUpdate);
    
    // 如果已连接，断开连接
    if (wsConnected.value) {
        disconnectChatWebSocket();
        wsConnected.value = false;
    }
});

const old = computed(() => {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    // 获取当前周的周一
    const currentMonday = new Date(currentWeekStart.value);
    currentMonday.setDate(currentMonday.getDate() - currentMonday.getDay() + 1);
    currentMonday.setHours(0, 0, 0, 0);
    
    // 获取当前周的周日
    const currentSunday = new Date(currentMonday);
    currentSunday.setDate(currentSunday.getDate() + 6);
    
    // 如果当前日期在当前周或未来周，则允许编辑（返回true）
    return today <= currentSunday;
});

/**
 * 获取指定周的课程表数据
 * 根据班级ID和日期范围查询课程安排
 */
async function getCurriculumSchedule() {
    try {
        // 获取当前周的周一日期
        const date = new Date(currentWeekStart.value);
        date.setDate(date.getDate() - date.getDay() + 1); // 设置为本周Monday
        const startDate = formatDate(date);
        
        // 获取当前周的周日日期
        const endDate = formatDate(new Date(date.getTime() + 6 * 86400000));
        
        // 调用后端API获取课程表数据
        const res = await getCurriculumScheduleService(classroomId.value, startDate, endDate);
        
        // 如果返回数据为空，初始化空课程表
        if (!res.data) {
            courseData.value = initCourseData();
            return;
        }

        // 处理返回的课程数据
        const scheduleData = res.data;
        
        // 初始化课程表数据结构
        courseData.value = initCourseData();

        // 遍历课程数据，填充到对应的时间段
        Object.entries(scheduleData).forEach(([day, schedules]) => {
            // 遍历每个时间段的课程
            for (let i = 0; i < 3; i++) {
                if (schedules[i]) {
                    // 将课程数据转换为字符串格式（用于el-select的value）
                    const course = schedules[i];
                    courseData.value[day][i] = JSON.stringify({
                        courseId: course.courseId,
                        courseName: course.courseName,
                        teacherId: course.teacherId,
                        teacherName: course.teacherName
                    });
                }
            }
            // 设置日期信息
            courseData.value[day][3] = schedules[3];
        });

        // 强制刷新下拉框组件
        refreshKey.value += 1;
    } catch (error) {
        console.error("获取课程表失败:", error);
        // 显示错误提示
        ElMessage.error("获取课程表失败，请重试");
    }
}

onMounted(async () => {
    classroomId.value = props.classroomId;
    classroomName.value = props.classroomName;
    updateCurrentDate();
    // 先获取课程列表
    await getCourseList();
    // 再获取课程表数据
    await getCurriculumSchedule();
    // 初始化 WebSocket 连接
    initWebSocket();
});
const params = reactive({
    classroomId: '',
})
const courseList = ref([])
const refreshKey = ref(0); // 用于强制刷新
async function getCourseList() {
    try {
        params.classroomId = classroomId.value
        const res = await getCourseListService(params);
        courseList.value = res.rows; // ✅ 正确赋值
        refreshKey.value += 1; // 强制刷新下拉框
    } catch (error) {
        console.error("加载教师列表失败:", error);
    }
}
// 初始化
onMounted(() => {
});
function getZH(day) {
    const translation = {
        0: '周一',
        1: '周二',
        2: '周三',
        3: '周四',
        4: '周五',
        5: '周六',
        6: '周天'
    };
    return translation[day];
}

const classroomId = ref('');
const classroomName = ref('');

const props = defineProps({
    classroomId: {
        type: String,
        required: true
    },
    classroomName: {
        type: String,
        required: true
    }
});

const days = ['0','1', '2', '3', '4', '5', '6'];
const times = ['上午(9:00-12:00)', '下午(14:00-17:00)', '晚上(19:00-22:00)'];

const currentDate = ref('');

// const ss = ref([['','','',''],['','','',''],['','','',''],['','','',''],['','','',''],['','','',''],['','','','']]);
const courseData = ref({
    0: [null, null, null, null],
    1: [null, null, null, null],
    2: [null, null, null, null],
    3: [null, null, null, null],
    4: [null, null, null, null],
    5: [null, null, null, null],
    6: [null, null, null, null]
});

/**
 * 初始化课程表数据结构
 * @returns {Object} 初始化后的课程表数据结构
 */
function initCourseData() {
    return {
        0: [null, null, null, null],
        1: [null, null, null, null],
        2: [null, null, null, null],
        3: [null, null, null, null],
        4: [null, null, null, null],
        5: [null, null, null, null],
        6: [null, null, null, null]
    };
}

// 获取当前日期并格式化
const formatDate = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
};


// 获取指定星期几的日期
const getDayDate = (day) => {
    const date = new Date(currentWeekStart.value);
    // 设置为本周的Monday
    date.setDate(date.getDate() - date.getDay() + 1);
    // 根据星期几计算具体日期
    const dayIndex = ['0', '1', '2', '3', '4', '5', '6'].indexOf(day);
    date.setDate(date.getDate() + dayIndex);
    return formatDate(date);
};

// 更新当前日期显示
const updateCurrentDate = () => {
    const date = new Date(currentWeekStart.value);
    date.setDate(date.getDate() - date.getDay() + 1); // 本周Monday
    currentDate.value = `第${getWeekNumber(date)}周 (${formatDate(date)} 至 ${formatDate(new Date(date.getTime() + 6 * 86400000))})`;
};

// 获取周数
const getWeekNumber = (date) => {
    const firstDayOfYear = new Date(date.getFullYear(), 0, 1);
    const pastDaysOfYear = (date - firstDayOfYear) / 86400000;
    return Math.ceil((pastDaysOfYear + firstDayOfYear.getDay() + 1) / 7);
};

// 上一周
const prevWeek = () => {
    currentWeekStart.value = new Date(currentWeekStart.value.getTime() - 7 * 86400000);
    updateCurrentDate();
    getCurriculumSchedule();
};

// 下一周
const nextWeek = () => {
    currentWeekStart.value = new Date(currentWeekStart.value.getTime() + 7 * 86400000);
    updateCurrentDate();
    getCurriculumSchedule();
};

// 判断是否是本周
const isCurrentWeek = computed(() => {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const currentMonday = new Date(currentWeekStart.value);
    currentMonday.setDate(currentMonday.getDate() - currentMonday.getDay() + 1);
    currentMonday.setHours(0, 0, 0, 0);
    const nextMonday = new Date(currentMonday.getTime() + 7 * 86400000);
    return today >= currentMonday && today < nextMonday;
});

// 判断日期是否在今天之前（过去的日期）
const isDateBeforeToday = (dateString) => {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    const date = new Date(dateString);
    date.setHours(0, 0, 0, 0);
    
    return date < today;
};

const submitCourseTable = async () => {
    // 获取当前周的Monday和Sunday日期
    const date = new Date(currentWeekStart.value);
    date.setDate(date.getDate() - date.getDay() + 1); // 本周Monday

    const startDate = formatDate(date);
    const endDate = formatDate(new Date(date.getTime() + 6 * 86400000));

    // 为每一天添加日期信息
    for (let i = 0; i < 7; i++) {
        const dayDate = new Date(date);
        dayDate.setDate(dayDate.getDate() + i);
        const ret = formatDate(dayDate);
        courseData.value[days[i]][3] = ret;
    }

    // 过滤空数据并处理课程数据
    const temp = JSON.parse(JSON.stringify(courseData.value));
    const keys = Object.keys(temp);
    keys.forEach(day => {
        if (temp[day][0] === null &&
            temp[day][1] === null &&
            temp[day][2] === null) {
            delete temp[day];
        } else {
            // 处理每个时间段的课程数据
            for (let i = 0; i < 3; i++) {
                if (temp[day][i]) {
                    try {
                        temp[day][i] = JSON.parse(temp[day][i]);
                    } catch (e) {
                        console.error('课程数据解析失败:', e);
                    }
                }
            }
        }
    });

    try {
        await updateCurriculumScheduleService(startDate, endDate, classroomId.value, classroomName.value, temp);
        alert('提交成功！');
    } catch (error) {
        console.error('提交失败:', error);
        alert('提交失败，请重试。');
    }
};

</script>

<style scoped>
/* 整体容器样式 */
.course-table-container {
    background-color: #e7f1ff;
    /* 浅蓝色背景 */
    padding: 20px;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 日期头部样式 */
.date-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    background-color: #d3e0ea;
    /* 浅蓝色背景 */
    padding: 10px 15px;
    border-radius: 8px;
}

.current-date {
    font-weight: bold;
    color: #333;
}

.week-navigation button {
    background-color: #4a90e2;
    /* 深蓝色按钮 */
    color: white;
    border: none;
    border-radius: 6px;
    padding: 5px 10px;
    margin-left: 10px;
    cursor: pointer;
}

.week-navigation button:hover {
    background-color: #3c7cd6;
}

/* 表格样式 */
table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 20px;
    background-color: white;
    /* 白色表格背景 */
    border: 1px solid #d3e0ea;
    /* 浅蓝色边框 */
}

th,
/* 时间单元格单独设置宽度 */
td:first-child {
    width: 150px;
    /* 设置时间单元格宽度为150px */
    padding: 12px 20px;
    /* 增加左右padding */
}
td {
    border: 1px solid #d3e0ea;
    opacity: 1;
    /* 浅蓝色边框 */
    padding: 12px;
    text-align: center;
    color: #333;
    /* 深灰色文字 */
}

th {
    background-color: #d3e0ea;
    /* 浅蓝色表头 */
    font-weight: bold;
}

/* 输入框样式 */
input {
    width: 90%;
    padding: 6px;
    text-align: center;
    border: 3px solid #d3e0ea;
    /* 浅蓝色边框 */
    border-radius: 4px;
    background-color: #f8faff;
    /* 浅蓝色背景 */
    color: #333;
    /* 深灰色文字 */
}

/* 按钮样式 */
.buttons {
    display: flex;
    justify-content: flex-end;
}

button {
    margin-right: 10px;
    padding: 10px 20px;
    background-color: #4a90e2;
    /* 深蓝色按钮 */
    color: white;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-weight: bold;
}

button:hover {
    background-color: #3c7cd6;
    /* 按钮悬停颜色 */
}

.select_btn .el-select {
    width: 100%;
}

/* 禁用状态的单元格样式 */
.select_btn:has(.el-select[disabled]) {
    background-color: #f5f5f5;
    cursor: not-allowed;
}

</style>